//
//  HMOAuthViewController.swift
//  Weibo12
//
//  Created by HM on 15/12/29.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD

// appkey
var WB_APPKEY = "2838588398"
// 回调地址
var WB_REGIRECTURI = "http://www.itheima.com/"

var WB_SECRET = "e32131d41a9f6a291a95b4ec83f24ef2"

class HMOAuthViewController: UIViewController, UIWebViewDelegate {

    override func loadView() {
        view = webView
        setupUI()
        // webView 加载链接
        // 请求地址
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REGIRECTURI)"
        // 生成 url
        let url = NSURL(string: urlString)!
        
        // 通过 url 生成 request
        let request = NSURLRequest(URL: url)
        
        // 使 webView 加载这个 request
        webView.loadRequest(request)
    }
    
    
    private func setupUI(){
        navigationItem.title = "新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFill")
    }
    
    // MARK: - 监听方法
    
    @objc private func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 自动填充
    @objc private func autoFill(){
        
        /**
        document.getElementById('userId').value='ssssss';
        document.getElementById('passwd').value='aaaaa';
        */
        // JS 注入
        let jsString = "document.getElementById('userId').value='372398930@qq.com';document.getElementById('passwd').value='zhao372398930';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    // MARK: - 懒加载控件
    private lazy var webView: UIWebView = {
        let webView = UIWebView()
        webView.delegate = self
        return webView
    }()
}


// MARK: - UIWebViewDelegate
extension HMOAuthViewController {
    // 可根据实际情况，判断是否要让 webView 加载这个链接
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else {
            return true
        }
        // 只要判断到是 ：http://www.itheima.com/?code=45c17a9372eb6678b1866ff57cdeed63 ，那么我们返回 false
        if !urlString.hasPrefix(WB_REGIRECTURI) {
            return true
        }
        
        // 代码执行到这个地方，就代表当前 urlString 是回调页
        if let query = request.URL?.query where query.hasPrefix("code="){
            print(query)
            // 截取 code
            let code = query.substringFromIndex("code=".endIndex)
            HMUserAccountViewModel.sharedViewModel.loadAccessToken(code, compeleted: { (isSuccess) -> () in
                if isSuccess {
                    print("请求完成要做的事情,切换控制器")
                    
                    SVProgressHUD.dismiss()
                    // 把当前界面消失之后再发送切换根控制器的通知
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(HMSwitchRootViewControllerNotification, object: self)
                    })
                    // 跳转到欢迎页
                    
                }else{
                    print("请求失败")
                }
            })
            // loadAccessToken(code)
        }else{
            // 用户点击取消
            // 关闭界面
            close()
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
